import { Form, Input } from 'antd';
import type { SearchProps } from 'antd/es/input';
import { useEffect, useRef, useState } from 'react';
import { useLibStore } from './useLibStore';

const { Search } = Input;

type OnSearchEventHandler = SearchProps['onSearch'];
type OnChangeEventHandler = SearchProps['onChange'];

export function LibSearchBox() {
  const { query, setQuery } = useLibStore();
  const [innerQuery, setInnerQuery] = useState(query);
  const queryRef = useRef({ innerQuery: query });

  const handleSearch: OnSearchEventHandler = (v, e, info) => {
    setQuery(v);
  };

  const handleChange: OnChangeEventHandler = (e) => {
    setInnerQuery(e.target.value);
  };

  useEffect(() => {
    if (query !== queryRef.current.innerQuery) {
      setInnerQuery(query);
    }
  }, [query]);

  useEffect(() => {
    queryRef.current.innerQuery = innerQuery;
  }, [innerQuery]);

  return (
    <Form>
      <Search
        placeholder='input search text'
        allowClear
        enterButton='Search'
        size='large'
        value={innerQuery}
        onChange={handleChange}
        onSearch={handleSearch}
        style={{ marginBottom: 20 }}
      />
    </Form>
  );
}
